package pers.yurwisher.rubick.oauth2.support;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStoreSerializationStrategy;
import pers.yurwisher.rubick.common.serializer.CustomGenericFastJsonRedisSerializer;

/**
 *
 * @author yq
 * @date 2021/04/16 21:47
 * @since V1.0.0
 * @description 自定义缓存序列化策略
 */
public class CustomTokenStoreSerializationStrategy implements RedisTokenStoreSerializationStrategy {

    private final RedisSerializer<String> keySerializer;
    private final CustomGenericFastJsonRedisSerializer valueSerializer;

    public CustomTokenStoreSerializationStrategy(RedisTemplate<String, Object> redisTemplate) {
        //缓存redis的Serializer 参照RedisConfig中配置
        this.valueSerializer = (CustomGenericFastJsonRedisSerializer) redisTemplate.getDefaultSerializer();
        this.keySerializer = (StringRedisSerializer) redisTemplate.getKeySerializer();
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> T deserialize(byte[] bytes, Class<T> aClass) {
        return (T) valueSerializer.deserialize(bytes);
    }

    @Override
    public String deserializeString(byte[] bytes) {
        return keySerializer.deserialize(bytes);
    }

    @Override
    public byte[] serialize(Object o) {
        return valueSerializer.serialize(o);
    }

    @Override
    public byte[] serialize(String s) {
        return keySerializer.serialize(s);
    }
}
